{- This file is part of funbot.
 -
 - Written in 2015 by fr33domlover <fr33domlover@rel4tion.org>.
 -
 - ♡ Copying is an act of love. Please copy, reuse and share.
 -
 - The author(s) have dedicated all copyright and related and neighboring
 - rights to this software to the public domain worldwide. This software is
 - distributed without any warranty.
 -
 - You should have received a copy of the CC0 Public Domain Dedication along
 - with this software. If not, see
 - <http://creativecommons.org/publicdomain/zero/1.0/>.
 -}

module FunBot.Sources.FeedWatcher
    ( feedWatcherSource
    )
where

import Data.Maybe (fromMaybe)
import Data.Time.Units
import FunBot.Config (feedVisitInterval)
import FunBot.ExtEvents (ExtEvent (NewsEvent), NewsItem (..))
import FunBot.Types
import Network.IRC.Fun.Bot.Logger
import Text.Feed.Query
import Web.Feed.Collect

import qualified Data.HashMap.Lazy as M

makeItem label ftitle item = NewsEvent $ NewsItem
    { itemFeedLabel = label
    , itemFeedTitle = Just ftitle
    , itemTitle     = fromMaybe "(no title)" $ getItemTitle item
    , itemAuthor    = getItemAuthor item
    , itemUrl       = getItemLink item
    }

collect push label _url feed item =
    push $ makeItem label (getFeedTitle feed) item

logError logger label err = logLine logger $ label ++ " : " ++ show err

feedWatcherSource :: FilePath -> BotState -> ExtEventSource
feedWatcherSource file state _config env push _pushMany mkLogger = do
    logger <- mkLogger file
    let cq = feedCmdQueue env
        pairs = M.toList $ watchedFeeds $ bsSettings state
        mkfeed (label, nf) = (label, nfUrl nf)
        feeds = map mkfeed pairs
        offs = [label | (label, nf) <- pairs, not $ nfActive nf]
    sendCommands cq $ map (flip feedActive False) offs
    putStrLn "Bot: Feed watcher source loop running"
    run
        (collect push)
        Nothing
        (logError logger)
        (Just cq)
        feedVisitInterval
        3
        feeds
